'''
                           _ooOoo_
                         o8888888o
                           88" . "88
                            (| ^_^ |)
                           O\  =  /O
                      ____/`---'\____
                          .'  \\|     |//  `.
                         /  \\|||  :  |||//  \
                       /  _||||| -:- |||||-  \
                        |   | \\\  -  /// |   |
                       | \_|  ''\---/''  |   |
                     \  .-\__  `-`  ___/-. /
                  ___`. .'  /--.--\  `. . ___
           ."" '<  `.___\_<|>_/___.'  >'"".
                | | :  `- \`.;`\ _ /`;.`/ - ` : | |
              \  \ `-.   \_ __\ /__ _/   .-` /  /
         佛祖保佑       永无BUG     永不修改
 '''

#广工赛摄像头代码
#库导入
import sensor, image, time, pyb
from machine import UART
from pyb import LED

#LED初始化
led1 = pyb.LED(1) #红
led2 = pyb.LED(3) #蓝
led3 = pyb.LED(2) #绿

# 初始化摄像头
sensor.reset()  # 初始化摄像头
sensor.set_pixformat(sensor.RGB565)  # 选择像素模式 RGB565.
sensor.set_framesize(sensor.QVGA)  # use QQVGA for speed.
sensor.set_auto_whitebal(False)  # 关闭白平衡。白平衡是默认开启的，在颜色识别中，需要关闭白平衡.
sensor.set_vflip(True)
sensor.skip_frames(time=1000)  # Let new settings take effect.

#时钟初始化
clock = time.clock()

#uart初始化
uart = UART(3,2400)
uart.init(2400, bits=8, parity=None, stop=1)

#数据打包
def outuart(R,G,B):
    global uart
    #发送数据
    uart.write('@')
    uart.write(str(R))
    uart.write(',')
    uart.write(str(G))
    uart.write(',')
    uart.write(str(B))
    uart.write(',')
    uart.write('\r\n')

def outuart2(databack):
    global uart
    #发送数据
    uart.write('@')
    uart.write(str(databack))
    uart.write(',')
    uart.write('\r\n')

#找出返回色块列表中最大色块
def findMaxBlob(blobs):
    MaxSize = 0
    for blob in blobs:
            if blob[2]*blob[3] >= MaxSize:
                MaxSize = blob[2]*blob[3]
                MaxBlob = blob
    return MaxBlob

#颜色识别感兴趣区域
roil = [170, 150, 60, 60]

# 定义颜色阈值
red_threshold = (30, 64, 37, 106, -2, 125)
blue_threshold = (21, 65, 1, 46, -75, -30)
green_threshold = (51, 78, -59, -28, -15, 50)

#标志位
Begin1= 0                   #启动标志位
flag1 = 0                     #第二次找色卡标志位
Red = 0
Green = 0
Blue = 0

#变量
databack = 'A'                  #返回32数据
time  = 0
data1 = 0                         #接收数据

color_to_detect = None  # 初始状态下未选择要检测的颜色
colors_to_detect = ["red", "blue", "green"]
color_detected = None  # 用于记录最近检测到的颜色

while(1):
       if uart.any():
           data1 = uart.readline()
           if data1 == b'B':
               Begin1 = 1
               led1.on()
               led2 .on()
               led3.on()

               while(Begin1):
                   clock.tick()
                   img = sensor.snapshot()
                   img.draw_rectangle(roil)#画出识别区域(矩形)

                   for color in colors_to_detect:
                       if color_to_detect is None:
                           red_blobs = img.find_blobs([red_threshold], area_threshold=400, roi=(150, 150, 60, 60))
                           blue_blobs = img.find_blobs([blue_threshold], area_threshold=400, roi=(150, 150, 60, 60))
                           green_blobs = img.find_blobs([green_threshold], area_threshold=400, roi=(150, 150, 60, 60))

                           if blue_blobs:
                                MaxBlob1 = findMaxBlob(blue_blobs)
                                if MaxBlob1.pixels()>=800:
                                    color_to_detect = "blue"
                                    color_detected = "blue"
                                    Blue = 1
                                    print("blue")
                                    outuart(0,0,1)
                                    time.sleep_ms(500)

                           elif red_blobs:
                               MaxBlob2 = findMaxBlob(red_blobs)
                               if MaxBlob2.pixels()>=800:
                                   color_to_detect = "red"
                                   color_detected = "red"
                                   print("red")
                                   Red = 1
                                   outuart(1,0,0)
                                   time.sleep_ms(500)

                           elif green_blobs:
                               MaxBlob3 = findMaxBlob(green_blobs)
                               if MaxBlob3.pixels()>=800:
                                   color_to_detect = "green"
                                   color_detected = "green"
                                   Green = 1
                                   time += 1
                                   print("green")
                                   outuart(0,1,0)
                                   time.sleep_ms(500)

                       color_to_detect = None










